<?php

class LAT_Controller extends MX_Controller {

	function LAT_Controller() {
		parent::__construct();
	}

	/* Reroute so index is used when no other method is found */
	public function _remap($method) {

		if($this->input->post('json') || $this->input->post('submit')) {

			$this->layout->output_type = 'json';

		}

		$uri = $this->uri->segment_array();

		// Redirect to default controller
		if(empty($uri)) {

			$this->layout->redirect($this->store->data('vars', 'index'), $this->layout->output_type);

		}
		// Run whatever the uri says
		else {

			if(!method_exists($this, $method))
			{

				$method = "index";
				$this->uri->segments = array_merge((array)$this->uri->segments[1], (array)'index', array_slice($this->uri->segments, 1));
				array_unshift($this->uri->segments, '');

				$this->uri->rsegments = array_merge((array)$this->uri->rsegments[1], (array)'index', array_slice($this->uri->rsegments, 1));
				array_unshift($this->uri->rsegments, '');

				unset($this->uri->rsegments[0], $this->uri->segments[0]);

			}

			call_user_func_array(array(&$this, $method), array_slice($this->uri->rsegment_array(), 2));

			$this->render($this->output->get_output(), $this->layout->output_type);
		}

	}

	function render($output, $type, $redirect=false) {

		// Debug output
		if(ENVIRONMENT == 'development') {
			$this->load->library('profiler');
			$output .= $this->profiler->run();
			$output = substr($output, 0, strlen($output) - 6);
			$output = $output.'<div id="ci_close" onclick="$(\'#codeigniter_profiler\').hide();">CLOSE DEBUG WINDOW</div><a href="'.site_url('forum/reload').'" rel="internal" style="font-size: 30px;">RELOAD STORES</a></div><div id="ci_open" onclick="$(\'#codeigniter_profiler\').show();">dev</div>';
		}

		$data = $this->layout->data;

		if(!$this->input->post('submit') || $redirect) {
			$data['output'] = $output;
		}

		switch($type) {

			case 'wrapper':
				$data['css'] = $this->layout->css;
				$output = $this->load->view('wrapper', $data, true);
				break;

			case 'json':
				$output = json_encode($data);
				break;

			case 'array':
				$output = $data;
				break;

			default:
				$output = $data['output'];
				break;

		}

		$this->output->set_output($output);
		return $output;

	}
}